<template>
  <div class="orders-container">
    <h2>订单管理</h2>
    
    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待付款" value="待付款" />
            <el-option label="待发货" value="待发货" />
            <el-option label="待收货" value="待收货" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table :data="orders" style="width: 100%">
      <el-table-column prop="id" label="订单编号" width="120" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column label="订单内容">
        <template #default="{ row }">
          <div v-for="item in row.items" :key="item.drugId" class="order-item">
            {{ item.drugName }} x {{ item.quantity }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额">
        <template #default="{ row }">
          ¥{{ row.totalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button 
            v-if="row.status === '待发货'"
            type="primary" 
            size="small" 
            @click="handleShip(row)"
          >
            发货
          </el-button>
          <el-button 
            type="info" 
            size="small" 
            @click="showOrderDetail(row)"
          >
            详情
          </el-button>
          <el-button 
            v-if="row.status === '待付款'"
            type="danger" 
            size="small" 
            @click="handleCancel(row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-item">
          <span class="label">订单编号：</span>
          <span>{{ currentOrder.id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">用户信息：</span>
          <span>{{ currentOrder.username }} ({{ currentOrder.phone }})</span>
        </div>
        <div class="detail-item">
          <span class="label">收货地址：</span>
          <span>{{ currentOrder.address }}</span>
        </div>
        <div class="detail-item">
          <span class="label">订单状态：</span>
          <el-tag :type="getStatusType(currentOrder.status)">{{ currentOrder.status }}</el-tag>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span>{{ currentOrder.createTime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">商品清单：</span>
          <div class="order-items">
            <div v-for="item in currentOrder.items" :key="item.drugId" class="item">
              <span>{{ item.drugName }}</span>
              <span>x {{ item.quantity }}</span>
              <span>¥{{ item.price.toFixed(2) }}</span>
            </div>
          </div>
        </div>
        <div class="detail-item total">
          <span class="label">总金额：</span>
          <span class="amount">¥{{ currentOrder.totalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrders, updateOrder } from '../../api'

export default {
  name: 'AdminOrders',
  setup() {
    const orders = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const detailDialogVisible = ref(false)
    const currentOrder = ref(null)
    
    const searchForm = reactive({
      orderId: '',
      username: '',
      status: ''
    })

    const getStatusType = (status) => {
      const statusMap = {
        '待付款': 'warning',
        '待发货': 'info',
        '待收货': 'primary',
        '已完成': 'success',
        '已取消': 'danger'
      }
      return statusMap[status] || 'info'
    }

    const loadOrders = async () => {
      try {
        const { data } = await getOrders({
          ...searchForm,
          page: currentPage.value,
          pageSize: pageSize.value
        })
        orders.value = data.items
        total.value = data.total
      } catch (error) {
        ElMessage.error('获取订单列表失败')
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadOrders()
    }

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      handleSearch()
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadOrders()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadOrders()
    }

    const handleShip = async (order) => {
      try {
        await ElMessageBox.confirm('确定要发货吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await updateOrder(order.id, { status: '待收货' })
        ElMessage.success('发货成功')
        loadOrders()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('发货失败')
        }
      }
    }

    const handleCancel = async (order) => {
      try {
        await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await updateOrder(order.id, { status: '已取消' })
        ElMessage.success('订单已取消')
        loadOrders()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消订单失败')
        }
      }
    }

    const showOrderDetail = (order) => {
      currentOrder.value = order
      detailDialogVisible.value = true
    }

    onMounted(() => {
      loadOrders()
    })

    return {
      orders,
      searchForm,
      currentPage,
      pageSize,
      total,
      detailDialogVisible,
      currentOrder,
      getStatusType,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleShip,
      handleCancel,
      showOrderDetail
    }
  }
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-item {
  margin: 5px 0;
}

.order-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.order-items {
  margin-top: 10px;
  border-top: 1px solid #EBEEF5;
  padding-top: 10px;
}

.order-items .item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  color: #606266;
}

.total {
  margin-top: 20px;
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

.amount {
  color: #F56C6C;
  font-size: 18px;
  font-weight: bold;
}
</style> 